import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { setName, getName, removeName } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: getName(),
  avatar: '',
  info: ''
}

const mutations = {
  setToken: (state, token) => {
    state.token = token
  },
  setName: (state, name) => {
    state.name = name
  },
  setAvatar: (state, avatar) => {
    state.avatar = avatar
  },
  setInfo: (state, info) => {
    state.info = info
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username, password: password }).then(response => {
        const { datas } = response.data
        const name = datas[0]
        const token = datas[1]
        const avatar = datas[2].avatarUrl
        commit('setName', name)
        commit('setToken', token)
        commit('setAvatar', avatar)
        setToken(token)
        setName(name)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({ username: state.name }).then(response => {
        const { datas } = response.data
        if (!datas) {
          reject('认证失败, 请重新登录')
        }
        const userBaseInfo = datas[0]
        const userCostomInfo = datas[1]
        commit('setInfo', userBaseInfo)
        commit('setAvatar', userCostomInfo.avatarUrl)
      }).catch(error => {
        reject(error)
      })
    })
  },

  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout({ username: state.name }).then(() => {
        commit('setToken', '')
        removeToken()
        removeName()
        resetRouter()
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('setToken', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
